//
//  Http.m
//  CherryPlumStore
//
//  Created by SDX on 2019/9/21.
//  Copyright © 2019 千凯. All rights reserved.
//

#import "Http.h"
#import <AFNetworking/AFNetworking.h>
@interface Http ()
+ (NSString *)appendUrl:(NSString *)url;
@end

@implementation Http

+ (void)getWithUrl:(NSString *)url WithParams:(NSDictionary *)params WithSuccessBlock:(SuccessBlock)successBlock WithFailBlock:(FailBlock)failBlock {
    NSString *api = [self appendUrl:url];
    // 创建manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager GET:api parameters:params progress:^(NSProgress *_Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
        NSLog(@"error---%@",error);
        failBlock(@"error");
    }];
}

+ (void)postWithUrl:(NSString *)url WithParams:(NSDictionary *)params WithSuccessBlock:(SuccessBlock)successBlock WithFailBlock:(FailBlock)failBlock {
    NSString *api = [self appendUrl:url];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    
    [manager POST:api parameters:params progress:^(NSProgress *_Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
        NSString *code = [responseObject valueForKey:@"code"];
        if ([code isEqualToString:@"1"]) {
            successBlock(responseObject);
        } else {
            NSString *msg = [responseObject valueForKey:@"msg"];
            NSLog(@"%@",msg);
        }
    } failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
        NSLog(@"error---%@",error);
        failBlock(@"error");
    }];
}

/**
 返回拼接后的url

 @param url 接口
 @return host
 */
+ (NSString *)appendUrl:(NSString *)url {
    return [HOST stringByAppendingString:url];
}

@end
